﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SumThenMod
{
    public class Util
    {
        #region HexToByte
        /// <summary>
        /// HexToByte
        /// </summary>
        public static byte[] HexStringToByte(string msg)
        {
            msg = msg.Replace(" ", "");
            byte[] comBuffer = new byte[msg.Length / 2];
            for (int i = 0; i < msg.Length; i += 2)
                comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
            return comBuffer;
        }
        #endregion

        #region ByteToHex
        /// <summary>
        /// ByteToHex
        /// </summary>
        public static string ByteToHexString(byte[] comByte)
        {
            StringBuilder builder = new StringBuilder();
            foreach (byte data in comByte)
                builder.Append(data.ToString("X2") + " ");
            //builder.Append(Convert.ToString(data, 16).PadLeft(2, '0'));
            return builder.ToString().ToUpper();
        }

        /// <summary>
        /// 根据输入，增加cs和帧尾
        /// </summary>
        /// <param name="src"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static byte[] GetSumThenMod256(string src, int startIndex)
        {
            var res = new List<byte>();
            byte[] db = HexStringToByte(src);
            if (db.Length > 0)
            {
                byte cs = (byte)(db.Skip(startIndex).Sum(x => x) % 256);
                res.AddRange(db);
                res.Add(cs);
                res.Add(0x16);
            }
            return res.ToArray();
        }
        #endregion
    }
}
